<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="catalogTreeData"
      row-key="catId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="name"
        label="目录名称"
        :show-overflow-tooltip="true"
        width="160"
      ></el-table-column>
      <el-table-column prop="sort" label="排序" width="60"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog
      :title="title"
      custom-class="dialog"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级目录" prop="parentCid">
              <treeselect
                v-model="form.parentCid"
                :options="catalogOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="目录名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCatalogList,
  getTreeStruct,
  addCatalog,
  getCatalogInfo,
  updateCatalog,
  deleteCatalog,
} from "@/api";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Catalog",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 目录表格树数据
      catalogTreeData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 目录树选项
      catalogOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentCid: [
          { required: true, message: "上级目录不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "目录名称不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "目录顺序不能为空", trigger: "blur" },
        ],
      },

      // 是否展开，默认全部折叠
      isExpandAll: false,

      // end
      // 显示搜索条件
      showSearch: true,

      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询目录列表 */
    getList() {
      this.loading = true;
      getCatalogList().then((res) => {
        console.log(res);
        this.catalogTreeData = res.data;
        this.loading = false;
      });
    },

    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.catId) {
        this.form.parentCid = row.catId;
      } else {
        this.form.parentCid = 0;
      }
      this.open = true;
      this.title = "添加菜单";
    },

    /** 查询目录下拉树结构 */
    getTreeselect() {
      getTreeStruct().then((res) => {
        this.catalogOptions = [];
        const mainCatalog = { id: 0, label: "主目录", children: [] };
        mainCatalog.children = res.data;
        this.catalogOptions.push(mainCatalog);
      });
    },

    /** 转换目录数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          if (this.form.catId != undefined) {
            updateCatalog(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCatalog(this.form).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentCid: 0,
        name: undefined,
        sort: undefined,
      };
      this.resetForm("form");
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getCatalogInfo(row.catId).then((res) => {
        this.form = res.data;
        this.open = true;
        this.title = "修改菜单";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return deleteCatalog(row.catId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
  },
};
</script>
